import React from 'react';
import {
  WebView,
  View,
  TouchableOpacity,
  Image,
  Text,
  Linking,
} from 'react-native';

import Orientation from 'react-native-orientation';

import Dimensions from 'Dimensions';
import BasePage from './BasePage';
import Constants from '../../common/Constants';
import SizeUtils from '../../common/SizeUtils';
import {HtmlUtils} from '../../utils/Utils';
import Config from '../../config';
import Platform from 'Platform';
var BGWASH = 'rgba(255,255,255,0.8)';

var TEXT_INPUT_REF = 'urlInput';

export default class WebViewPage extends BasePage {
  constructor(props) {
    super(props);

    this.state.status = 'No Page Loaded',
    this.state.backButtonEnabled = false,
    this.state.forwardButtonEnabled = false,
    this.state.loading = true,
    this.state.scalesPageToFit = true,
    this.state.orientation = "PORTRAIT";

    this._pageName = "WebViewPage";
    this._alwaysShowClose = false;

    this._webViewRef = null;

    this._lastUrl = "";

    this.patchPostMessageFunction = function() {
      var originalPostMessage = window.postMessage;
      var patchedPostMessage = function(message, targetOrigin, transfer) {
        originalPostMessage(message, targetOrigin, transfer);
      };
      patchedPostMessage.toString = function() {
        return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
      };
      window.postMessage = patchedPostMessage;
    };
    this.patchPostMessageJsCode = '(' + String(this.patchPostMessageFunction) + ')();';
  }

  _setUrl(url) {
    this.setState({
      url:url,
      source:{uri:url},
      isHas:true,
    });
    this._customUrl = url;
  }

  componentDidMount() {
    // Orientation.unlockAllOrientations();
    // Orientation.addOrientationListener(this._orientationDidChange.bind(this));
  }

  componentWillUnmount() {
    // Orientation.lockToPortrait();
    // Orientation.removeOrientationListener(this._orientationDidChange.bind(this));
    this.setState({
        url: "",
      });
  }

  _orientationDidChange(orientation){
    if (orientation == 'LANDSCAPE') {
      SizeUtils.changeLandscape();
      this.setState({Orientation:1});
      }else if(orientation == 'PORTRAITUPSIDEDOWN'){
        //屏幕向下
      }
      else {
        //do something with portrait layout
        SizeUtils.lockToPortrait();
        this.setState({Orientation:0});
      }
  }

  render() {
    return(
      <View style={{width:SizeUtils.getWindowSize().width, height:SizeUtils.getWindowSize().height,
         paddingTop: Config.paddingTop, backgroundColor:"#ffffff"}}>
         {this.renderWebView()}
        { this._renderNavigationBar()}
      </View>
    )
  }

  isRenderWebView(){
    return this.state.isHas;
  }


  renderWebView(){
    if(this.isRenderWebView()){
      return (<WebView
            ref={this._initRef.bind(this)}
            automaticallyAdjustContentInsets={true}
            style={{width:SizeUtils.getWindowSize().width,
              height:SizeUtils.getWindowSize().height - Config.paddingTop,}}
            source={this._getSource()}
            javaScriptEnabled={true}
            allowsInlineMediaPlayback={true}
            domStorageEnabled={true}
            scalesPageToFit={this.state.scalesPageToFit}
            onNavigationStateChange={this._onNavigationStateChange.bind(this)}
            onLoad={this._onWebLoad.bind(this)}
            onError={this._onError.bind(this)}
            injectedJavaScript={this._injectedJavaScript()}
            onMessage={this._onWebViewMessage.bind(this)}
            onLayout={this._onWebViewLayout.bind(this)}
            onShouldStartLoadWithRequest={this._onShouldStartLoadWithRequest.bind(this)}
            renderError={this._onRenderError.bind(this)}
          />)
    }else {
      return (
       <View style={{width:SizeUtils.getWindowSize().width, paddingTop:SizeUtils.translateDesignHeightToCode(80),
          flexDirection:"row", justifyContent:"center"}}>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(30)}}></Text>
      </View>)
    }
  }

  _onRenderError(event) {
    // console.log(event);
    return (
      <View style={{flex:1, flexDirection:"row", alignItems:"center", justifyContent:"center"}}>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(30), textAlign:"center"}}>Loading...</Text>
      </View>
    )
  }

  _onWebViewLayout(event) {

  }

  _onWebViewMessage(event) {

  }

  _onWebLoad(event) {
    console.log("网页加载完毕:" + this.state.url);
  }

  _onError(event) {
    console.log("网页加载错误:" + this.state.url);
  }

  _injectedJavaScript() {
    // if(Platform.OS === "ios") {
    return this.patchPostMessageJsCode;
    // }
    // return `(function (doc, win) {
    //   var doc = win.document;
    //   var docEl = doc.documentElement;
    //   var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
    //   var metaEl = doc.querySelector('meta[name="viewport"]');
    //   var metaCtt = metaEl ? metaEl.content : '';
    //   var dpr = 0;
    //   var scale = 0;
    //   var matchScale = metaCtt.match(/initial\-scale=([\d\.]+)/);
    //   var matchWidth = metaCtt.match(/width=([^,\s]+)/);
    //
    //   /**
    //     * ================================================
    //     *   设置data-dpr和viewport
    //     × ================================================
    //     */
    //   if (matchScale) {
    //     console.warn('将根据已有的meta标签来设置缩放比例');
    //     scale = parseFloat(matchScale[1]);
    //     dpr = parseInt(1 / scale);
    //   }
    //
    //   // 对iOS设备进行dpr的判断，对于Android系列，始终认为其dpr为1
    //   if (!dpr && !scale) {
    //     var isAndroid = win.navigator.appVersion.match(/android/gi);
    //     var isIPhone = win.navigator.appVersion.match(/[iphone|ipad]/gi);
    //     var devicePixelRatio = win.devicePixelRatio;
    //     if (isIPhone) {
    //         // iOS下，对于2和3的屏，用2倍的方案，其余的用1倍方案
    //         if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
    //             // dpr = 3;
    //             dpr = 1;
    //         } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)){
    //             dpr = 1;
    //             // dpr = 2;
    //         } else {
    //             dpr = 1;
    //         }
    //     } else {
    //         // 其他设备下，仍旧使用1倍的方案
    //         dpr = 1;
    //     }
    //     scale = 1 / dpr;
    //   }
    //
    //   docEl.setAttribute('data-dpr', dpr);
    //   // 动态改写meta:viewport标签
    //   if (!matchScale) {
    //     var metaEl = doc.createElement('meta');
    //     metaEl.setAttribute('name', 'viewport');
    //     metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
    //     if (docEl.firstElementChild) {
    //       document.documentElement.firstElementChild.appendChild(metaEl);
    //     } else {
    //       var wrap = doc.createElement('div');
    //       wrap.appendChild(metaEl);
    //       documen.write(wrap.innerHTML);
    //     }
    //   }
    //
    // })(document, window);`;
  }

  _initRef(ref) {
    this._webViewRef = ref;
  }

  _getSource() {
    return this.state.source;
  }

  // _orientationDidChange(orientation) {
  //   console.log("webview", orientation);
  //   if(orientation == "LANDSCAPE") {
  //     Orientation.lockToLandscape();
  //     SizeUtils.changeLandscape();
  //   }
  //   else {
  //     Orientation.lockToPortrait();
  //     SizeUtils.lockToPortrait();
  //   }
  // }

  _dealAfterEnterAnimation() {
    this._setUrl(this.props.pageData.routeData.url);
  }

  _dealEnterPage() {
    super._dealEnterPage();
    Orientation.unlockAllOrientations();
  }

  _dealLeavePage(){
    super._dealLeavePage();
    Orientation.lockToPortrait();
    SizeUtils.lockToPortrait();
    setTimeout(()=>{
      this.setState({
        isHas:false,
      });
    }, 500);
    // this._setUrl("");
    // this.state.source = HtmlUtils.getHtmlWeb("", SizeUtils.getWindowSize().width);
  }

  _onNavigationStateChange(navState){
    // this.setState({
    //   backButtonEnabled: navState.canGoBack,
    //   forwardButtonEnabled: navState.canGoForward,
    //   url: navState.url,
    //   status: navState.title,
    //   loading: navState.loading,
    //   scalesPageToFit: true
    // });
    console.log("_onNavigationStateChange", navState.url, navState);
    // if(navState.url === "iting://open?msg_type=12&uid=34038734") {
    //   return;
    // }
    this._lastUrl = this.state.url;
    this.setState({
      url: navState.url,
    })
  }

  _onShouldStartLoadWithRequest(event) {
    return true;
  }

  _renderNavigationBarLeftButton() {
    return (
      <View style={{width:SizeUtils.translateDesignWidthToCode(200),
        flexDirection:"row",height:SizeUtils.translateDesignHeightToCode(66)}}>
        <TouchableOpacity onPress={this._onPressNavigationBarLeftBtn.bind(this)}
          disabled={!this.props.pageData.showLeftButton} style={{width:SizeUtils.translateDesignWidthToCode(100),
          paddingLeft:SizeUtils.translateDesignWidthToCode(40)}}>
            {this._renderNavigationBarLeftButtonContent()}
        </TouchableOpacity>
        <TouchableOpacity onPress={this._onPressCloseBtn.bind(this)}
          disabled={this.state.url == this._customUrl} style={{width:SizeUtils.translateDesignWidthToCode(100),
            paddingLeft:SizeUtils.translateDesignWidthToCode(20)}}>
            {this._renderCloseImage()}
        </TouchableOpacity>
      </View>
    )
  }

  _renderNavigationBarLeftButtonContent() {
    return (
      <Image source={require("../../../resource/images/common/Back-icon.png")}
          style={{width:SizeUtils.translateDesignWidthToCode(24),
            height:SizeUtils.translateDesignWidthToCode(41)}}/>
    )
  }

  _renderCloseImage() {
    if(this._alwaysShowClose === true || this.state.url != this._customUrl) {
      return(
        <Image source={require("../../../resource/images/common/cha.png")}
            style={{width:SizeUtils.translateDesignWidthToCode(40),
              height:SizeUtils.translateDesignWidthToCode(41)}}/>
      )
    }
  }

  _onPressCloseBtn() {
    this.goBack();
  }

  _onPressNavigationBarLeftBtn() {
    if(this.state.url != this._customUrl && this._webViewRef && this._lastUrl.indexOf("about:blank") < 0) {
      this._webViewRef.goBack();
    }
    else {
      this.goBack();
    }
  }
}
